package com.sinopec.handdevice.jpush;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;

import com.sinopec.basemodule.event.CustomerMsg;
import com.sinopec.basemodule.event.InformMsg;
import com.sinopec.basemodule.event.RxBus;
import com.sinopec.basemodule.router.ReflectUtils;
import com.sinopec.basemodule.utils.ARouterManagerUtils;
import com.sinopec.handdevice.MyApp;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Iterator;

import cn.jpush.android.api.JPushInterface;

/**
 * 自定义接收器
 * <p>
 * 如果不定义这个 Receiver，则：
 * 1) 默认用户会打开主界面
 * 2) 接收不到自定义消息
 */
public class MyReceiver extends BroadcastReceiver {
    private static final String TAG = MyReceiver.class.getName();
    private Context context;

    @Override
    public void onReceive(Context context, Intent intent) {
        this.context = context;
        try {
            Bundle bundle = intent.getExtras();
            Logger.d(TAG, "[MyReceiver] onReceive - " + intent.getAction() + ", extras: " + printBundle(bundle));

            if (JPushInterface.ACTION_REGISTRATION_ID.equals(intent.getAction())) {
                String regId = bundle.getString(JPushInterface.EXTRA_REGISTRATION_ID);
                Logger.d(TAG, "[MyReceiver] 接收Registration Id : " + regId);
                //send the Registration Id to your server...

            } else if (JPushInterface.ACTION_MESSAGE_RECEIVED.equals(intent.getAction())) {
                Logger.d(TAG, "[MyReceiver] 接收到推送下来的自定义消息: " + bundle.getString(JPushInterface.EXTRA_MESSAGE));
                //processCustomMessage(context, bundle);

            } else if (JPushInterface.ACTION_NOTIFICATION_RECEIVED.equals(intent.getAction())) {
                Logger.d(TAG, "[MyReceiver] 接收到推送下来的通知");
                JSONObject json = new JSONObject(bundle.getString(JPushInterface.EXTRA_EXTRA));
                String codeStr = json.optString("extraMsgType", "");
                switch (codeStr) {
                    case "100"://您有一条新的入库单【单号】，请尽快操作(收到极光刷新待入库列表)
                        RxBus.getInstanceBus().post(new InformMsg("refreshStockInListingFragment"));
                        break;
                    case "102":
                        //"102","待复核入库单"
                        RxBus.getInstanceBus().post(new InformMsg("refreshStockInListedFragment"));
                        break;
                    case "101"://您有一条新的出库单【单号】，请尽快操作(收到极光刷新待出库列表)
                        RxBus.getInstanceBus().post(new InformMsg("refreshStockOutListingFragment"));
                        break;
                    case "103":
                        //"103","待复核出库单"
                        RxBus.getInstanceBus().post(new InformMsg("refreshStockOutListedFragment"));
                        break;
                    default:
                        break;
                }
            } else if (JPushInterface.ACTION_NOTIFICATION_OPENED.equals(intent.getAction())) {
                Logger.d(TAG, "[MyReceiver] 用户点击打开了通知");

                JSONObject json = new JSONObject(bundle.getString(JPushInterface.EXTRA_EXTRA));

                String extraMsgType = json.optString("extraMsgType", "");
                //UserInfo userInfo = SaasApp.getInstance().getUserManager().getUser();
                String token = MyApp.getInstance().getToken();
                if ("0".equals(token)) {
                    //缓存中没有用户信息了打开通知直接跳主界面，否则跳相应的界面
                    ARouterManagerUtils.gotoLogin();
                } else {
                    switch (extraMsgType) {
                        case "100":
                            //入库单,跳转至入库-待入库界面
                            gotoHomeAndSwitchFragment(context, extraMsgType, 0, 0);
                            break;
                        case "102":
                            //"102","待复核入库单"
                            //入库单,跳转至入库-待入库界面
                            gotoHomeAndSwitchFragment(context, extraMsgType, 0, 1);
                            break;
                        case "101":
                            //出库单,跳转至出库-待出库界面
                            gotoHomeAndSwitchFragment(context, extraMsgType, 1, 0);
                            break;
                        case "103": {
                            //"103","待复核出库单"
                            //出库单,跳转至出库-待出库界面
                            gotoHomeAndSwitchFragment(context, extraMsgType, 1, 1);
                            break;
                        }
                    }
                }
            } else if (JPushInterface.ACTION_RICHPUSH_CALLBACK.equals(intent.getAction())) {
                Logger.d(TAG, "[MyReceiver] 用户收到到RICH PUSH CALLBACK: " + bundle.getString(JPushInterface.EXTRA_EXTRA));
                //在这里根据 JPushInterface.EXTRA_EXTRA 的内容处理代码，比如打开新的Activity， 打开一个网页等..
            } else if (JPushInterface.ACTION_CONNECTION_CHANGE.equals(intent.getAction())) {
                boolean connected = intent.getBooleanExtra(JPushInterface.EXTRA_CONNECTION_CHANGE, false);
                Logger.w(TAG, "[MyReceiver]" + intent.getAction() + " connected state change to " + connected);
            } else {
                Logger.d(TAG, "[MyReceiver] Unhandled intent - " + intent.getAction());
            }
        } catch (Exception e) {

        }
    }

    /**
     * 跳转到主界面，并跳转到对应要选择的fragment
     */
    private void gotoHomeAndSwitchFragment(Context context, String extraMsgType, int parentPosition, int childPosition) {
        RxBus.getInstanceBus().post(new CustomerMsg(extraMsgType, childPosition));
        ReflectUtils.navigationToHome(context, parentPosition);
    }

    // 打印所有的 intent extra 数据
    private static String printBundle(Bundle bundle) {
        StringBuilder sb = new StringBuilder();
        for (String key : bundle.keySet()) {
            if (key.equals(JPushInterface.EXTRA_NOTIFICATION_ID)) {
                sb.append("\nkey:" + key + ", value:" + bundle.getInt(key));
            } else if (key.equals(JPushInterface.EXTRA_CONNECTION_CHANGE)) {
                sb.append("\nkey:" + key + ", value:" + bundle.getBoolean(key));
            } else if (key.equals(JPushInterface.EXTRA_EXTRA)) {
                if (TextUtils.isEmpty(bundle.getString(JPushInterface.EXTRA_EXTRA))) {
                    Logger.i(TAG, "This message has no Extra data");
                    continue;
                }

                try {
                    JSONObject json = new JSONObject(bundle.getString(JPushInterface.EXTRA_EXTRA));
                    Iterator<String> it = json.keys();

                    while (it.hasNext()) {
                        String myKey = it.next();
                        sb.append("\nkey:" + key + ", value: [" +
                                myKey + " - " + json.optString(myKey) + "]");
                    }
                } catch (JSONException e) {
                    Logger.e(TAG, "Get message extra JSON error!");
                }

            } else {
                sb.append("\nkey:" + key + ", value:" + bundle.getString(key));
            }
        }
        return sb.toString();
    }

}
